import { createReducer } from './util';
import * as UserAction from '../actions/user';
import LoginUser from '../login-user';
import { browserHistory } from 'react-router';
import * as WebSocket from '../ws';
import _ from 'lodash';

export const loginUser = createReducer(on => {
  on(UserAction.login)
    .completed((state, action) => {
      WebSocket.connect();
      return new LoginUser(action.payload);
    });
  on(UserAction.logout)
    .completed(() => {
      WebSocket.disconnect();
      browserHistory.push('/index');
      return {};
    });
  on(UserAction.nativeLogout)
    .completed(() => {
      WebSocket.disconnect();
      browserHistory.push('/index');
      return {};
    });
  on(UserAction.getLogined)
    .completed((state, action) => {
      if (_.isEmpty(action.payload)) {
        WebSocket.disconnect();
        return {};
      }
      WebSocket.connect();
      return new LoginUser(action.payload);
    });
}, {});

export const searchUserList = createReducer(on => {
  on(UserAction.search);
}, {});

export const suggestUser = createReducer(on => {
  on(UserAction.suggest);
}, []);

export const userById = createReducer(on => {
  on(UserAction.getUserInfo);
}, {});
